<template>
  <div class="main">
    <!-- 头部栏 logo背景图片 -->
    <div class="backgroundimg"></div>

    <!-- 搜索栏 -->
    <div class="searchinput">
      <el-input
        :placeholder="defaultKeywords"
        v-model="searchKeywords"
        @focus="inputFoucs"
        @blur="inputBlur"
        @keyup.enter.native="toSearchPage(searchKeywords)"
        v-on:input="inputFoucs"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>

      <!-- 搜索选项框 -->
      <div class="searchItem" v-if="searchItemShow">
        <!-- 热搜榜 -->
        <div class="hotSearch" v-if="hotSearchShow">
          <div class="hotTxt">热搜榜</div>
          <ol>
            <li
              v-for="(hotDetailItem, key) in hotDetailList"
              :key="key"
              @click="toSearchPage(hotDetailItem.searchWord)"
            >
              <div>
                <span>{{ hotDetailItem.searchWord }}</span>
                <span>{{ hotDetailItem.score }}</span>
              </div>
              <div>{{ hotDetailItem.content }} &ensp;</div>
            </li>
          </ol>
        </div>

        <!-- 搜索建议 -->
        <div class="searchSuggest" v-if="searchSuggestShow">
          <div v-if="searchSuggestResult.guess.length != 0">
            <div><i class="el-icon-refrigerator"></i> 猜你想搜</div>
            <div
              v-for="(item, key) in searchSuggestResult.guess"
              :key="key"
              @click="toSearchPage(item.keyword)"
            >
              <span>{{ item.keyword }}</span>
            </div>
          </div>
          <div v-if="searchSuggestResult.songs.length != 0">
            <div><i class="el-icon-refrigerator"></i> 单曲</div>
            <div
              v-for="(item, key) in searchSuggestResult.songs"
              :key="key"
              @click="playSong(item)"
            >
              <span>{{ item.name }}</span> - <span>{{ item.artistName }}</span>
            </div>
          </div>
          <div v-if="searchSuggestResult.artists.length != 0">
            <div><i class="el-icon-cherry"></i> 歌手</div>
            <div
              v-for="(item, key) in searchSuggestResult.artists"
              :key="key"
              @click="toSongerDetailPage(item.id)"
            >
              <span>{{ item.name }} </span>
            </div>
          </div>
          <div v-if="searchSuggestResult.albums.length != 0">
            <div><i class="el-icon-orange"></i> 专辑</div>
            <div
              v-for="(item, key) in searchSuggestResult.albums"
              :key="key"
              @click="toAlbumlistPage(item.id)"
            >
              <span>{{ item.name }}</span> - <span>{{ item.artistName }}</span>
            </div>
          </div>
          <div v-if="searchSuggestResult.playlists.length != 0">
            <div><i class="el-icon-knife-fork"></i> 歌单</div>
            <div
              v-for="(item, key) in searchSuggestResult.playlists"
              :key="key"
              @click="toSonglistPage(item.id)"
            >
              <span>{{ item.name }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户头像栏 -->
    <div class="userinfo" @click="toUserDetailPage">
      <el-image
        style="width: 40px; height: 40px"
        :src="imageUrl"
        fit="fill"
      ></el-image>
      <div class="username">{{ username }}</div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'headbar',
  props: ['userId', 'imageUrl', 'username'],
  data() {
    return {
      // 默认关键字
      defaultKeywords: '',
      // 搜索关键字
      searchKeywords: '',
      // 热搜列表(详细)
      hotDetailList: [],
      // 搜索框显示与否
      searchItemShow: false,
      // 热搜榜显示与否
      hotSearchShow: false,
      // 搜索建议显示与否
      searchSuggestShow: false,
      // 搜索建议查询结果
      searchSuggestResult: {
        albums: [],
        artists: [],
        playlists: [],
        songs: [],
        // 搜索建议猜你想搜查询结果
        guess: [],
      },
    }
  },
  computed: {
    // ...mapState(['searchKeyWord']),
  },
  created() {
    this.getSearchDefault()
  },
  watch: {
    searchKeywords: function (newVal, oldVal) {
      if (this.searchKeywords == '') {
        this.getSearchDefault()
        return
      } else {
        this.getSearchSuggest()
        this.getSearchSuggestMobile()
        return
      }
    },
  },

  methods: {
    ...mapMutations([
      'changePath',
      'changeIsActive',
      'changeIsMyself',
      'changeSongerId',
      'changeSonglistId',
      'changeAlbumlistId',
      'changeMusicPlayInfo',
      'changeSearchKeyWord',
      'changeTheDetailUserId',
    ]),

    // 跳转到个人信息页面
    toUserDetailPage() {
      if (!window.sessionStorage.getItem('token')) {
        return this.$message.warning('请先登录！')
      }
      // console.log(this.userId)
      const info = {
        path: '/view/userdetail',
        isMyself: true,
        theDetailUserId: this.userId,
      }

      this.changePath(info.path)
      this.changeIsMyself(info.isMyself)
      this.changeTheDetailUserId(info.theDetailUserId)

      this.$emit('getUserDetailInfo')
    },
    // 输入框获得焦点事件
    inputFoucs() {
      this.searchItemShow = true
      if (this.searchKeywords == '') {
        this.hotSearchShow = true
        this.searchSuggestShow = false
        this.getSearchHotDetail()
        return
      }
      this.hotSearchShow = false
      this.searchSuggestShow = true
      this.getSearchSuggest()
      this.getSearchSuggestMobile()
    },
    // 输入框失去焦点事件
    inputBlur() {
      setTimeout(() => {
        this.searchItemShow = false
      }, 200)
    },
    // 获取默认搜索关键词
    async getSearchDefault() {
      const { data: res } = await this.$http({
        url: `/search/default`,
        withCredentials: true, //关键
      })
      // console.log(res)

      this.defaultKeywords = res.data.realkeyword
    },
    // 获取搜索建议
    async getSearchSuggest() {
      const { data: res } = await this.$http({
        url: `/search/suggest?keywords=${this.searchKeywords}`,
        withCredentials: true, //关键
      })
      // console.log(res)

      let albums = []
      let artists = []
      let playlists = []
      let songs = []
      if (res.result.albums) {
        res.result.albums.map((item) => {
          let listObj = {}

          listObj.id = item.id
          listObj.name = item.name
          listObj.artistName = item.artist.name

          return albums.push(listObj)
        })
      }
      if (res.result.artists) {
        res.result.artists.map((item) => {
          let listObj = {}

          listObj.id = item.id
          listObj.name = item.name

          return artists.push(listObj)
        })
      }
      if (res.result.playlists) {
        res.result.playlists.map((item) => {
          let listObj = {}

          listObj.id = item.id
          listObj.name = item.name

          return playlists.push(listObj)
        })
      }
      if (res.result.songs) {
        res.result.songs.map((item) => {
          let listObj = {}

          listObj.id = item.id
          listObj.time = item.duration
          listObj.name = item.name
          listObj.album = item.album.name
          listObj.picUrl = item.album.img1v1Url

          let str = ''
          for (let i = 0; i < item.artists.length; i++) {
            str = str + item.artists[i].name
            if (i != item.artists.length - 1) {
              str = str + '/'
            }
          }
          listObj.artistName = str

          return songs.push(listObj)
        })
      }

      this.searchSuggestResult.albums = albums
      this.searchSuggestResult.artists = artists
      this.searchSuggestResult.playlists = playlists
      this.searchSuggestResult.songs = songs
    },
    // 获取搜索建议(猜你想搜)
    async getSearchSuggestMobile() {
      const { data: res } = await this.$http({
        url: `/search/suggest?keywords=${this.searchKeywords}&type=mobile`,
        withCredentials: true, //关键
      })
      // console.log(res)

      let tempListDatas = []
      if (res.result.allMatch) {
        res.result.allMatch.map((item) => {
          let listObj = {}
          listObj.keyword = item.keyword
          return tempListDatas.push(listObj)
        })
      }

      this.searchSuggestResult.guess = tempListDatas
    },
    // 热搜列表(详细)
    async getSearchHotDetail() {
      const { data: res } = await this.$http({
        url: `/search/hot/detail`,
        withCredentials: true, //关键
      })
      // console.log(res)

      let tempListDatas = []
      res.data.map((item) => {
        let listObj = {}

        listObj.score = item.score
        listObj.content = item.content
        listObj.searchWord = item.searchWord

        return tempListDatas.push(listObj)
      })
      this.hotDetailList = tempListDatas
    },

    // 跳转到搜素结果页面
    toSearchPage(searchWords) {
      let searchKeywords = searchWords
      if (searchWords == '') {
        searchKeywords = this.defaultKeywords
      }
      this.searchKeywords = searchKeywords

      const info = {
        searchKeyWord: searchKeywords,
        isActive: '',
        path: '/view/search',
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)
      this.changeSearchKeyWord(info.searchKeyWord)

      this.$emit('getSearchPageInfo')

      setTimeout(() => {
        this.searchItemShow = false
      }, 200)
    },
    // 跳转到歌手详情页面
    toSongerDetailPage(songerId) {
      const info = {
        path: '/view/songerdetail',
        isActive: '',
        songerId: songerId,
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)
      this.changeSongerId(info.songerId)

      this.$emit('getSongerDetailInfo')
    },
    // 播放歌曲
    playSong(row) {
      let thePlaySongInfo = row
      let thePlaySongListInfo = []

      const info = {
        thePlaySongInfo,
        thePlaySongListInfo,
      }

      this.changeMusicPlayInfo(info)
    },
    // 传递 歌单数据，并跳转到歌单页面
    toSonglistPage(songlistId) {
      const info = {
        path: '/view/songlist',
        isActive: songlistId,
        songlistId: songlistId,
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)
      this.changeSonglistId(info.songlistId)

      this.$emit('getSonglistId')
    },
    // 传递 专辑数据，并跳转到专辑页面
    toAlbumlistPage(albumlistId) {
      const info = {
        path: '/view/albumlist',
        isActive: '',
        albumlistId: albumlistId,
      }

      this.changePath(info.path)
      this.changeIsActive(info.isActive)
      this.changeAlbumlistId(info.albumlistId)

      this.$emit('getAlbumlistId', info)
    },
  },
}
</script>

<style lang="less" scoped>
.main {
  width: 1200px;
  height: 66px;
  background-color: #ec4141;

  display: flex;
  justify-content: space-between;
}

// 左侧设置网易云背景logo
.backgroundimg {
  height: 100%;
  width: 160px;
  background-image: url('../../../assets/img/cloud.png');
  background-repeat: no-repeat;
  margin-left: 18px;
}

// 中部搜索框
.searchinput {
  width: 240px;
  height: 100%;
  position: relative;
  > .el-input {
    position: relative;
    top: 50%;
    transform: translate(0, -50%);
    /deep/ .el-input__inner {
      border-radius: 20px;
      background-color: #e13e3e;
      border: 0px;
      color: white;
    }
  }
  > .searchItem {
    z-index: 99;
    width: 360px;
    height: 500px;
    max-height: 500px;
    overflow: auto;
    background-color: white;
    position: relative;
    top: 32px;
    left: -52px;
    border-radius: 12px;
    box-shadow: -2px 2px 10px rgb(207, 197, 197);
    .hotSearch {
      .hotTxt {
        padding: 16px 0 0 16px;
        font-size: 18px;
        color: #676767;
      }
      ol {
        li {
          padding-top: 8px;
          padding-bottom: 8px;
          span {
            padding-right: 12px;
          }
          span:nth-child(2) {
            color: #d3c4d3;
            font-weight: normal;
          }
          div {
            padding-left: 12px;
            max-width: 280px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          div:nth-child(2) {
            color: #979797;
            font-weight: normal;
            font-size: 14px;
          }
        }
        li:hover {
          background-color: #f2f2f2;
        }
        li:nth-child(1) {
          color: #ff3a3a;
          font-weight: bold;
          span:nth-child(1) {
            color: black;
          }
        }
        li:nth-child(2) {
          color: #ff3a3a;
          font-weight: bold;
          span:nth-child(1) {
            color: black;
          }
        }
        li:nth-child(3) {
          color: #ff3a3a;
          font-weight: bold;
          span:nth-child(1) {
            color: black;
          }
        }
      }
    }

    .searchSuggest {
      > div {
        div {
          padding: 10px 0 10px 30px;
        }
        div:hover {
          background-color: #f2f2f2;
        }
        div:nth-child(1) {
          padding: 15px 0 15px 20px;
          color: #979797;
        }
        div:nth-child(1):hover {
          background-color: white;
        }
      }
    }
  }
}

// 右侧用户头像和用户昵称
.userinfo {
  height: 100%;
  width: 240px;
  display: flex;
  justify-content: flex-end;

  > .el-image {
    border-radius: 50%;
    position: relative;
    top: 50%;
    transform: translate(0, -50%);
  }
  > .username {
    height: 28px;
    position: relative;
    top: 50%;
    transform: translate(0, -50%);
    margin-left: 10px;
    margin-right: 18px;
    font-size: 16px;
    color: white;
  }
}
</style>